'use strict'

// Import required modules
require('dotenv').config()
const path = require('node:path')
const fastify = require('fastify')

// Create Fastify instance with V5 configuration
const app = fastify({
  logger: {
    level: process.env.LOG_LEVEL || 'info',
    transport: {
      target: 'pino-pretty'
    }
  }
})

// Register MongoDB plugin
app.register(require('@fastify/mongodb'), {
  url: process.env.MONGODB_URI
})

// Register Swagger plugins
app.register(require('@fastify/swagger'), {
  openapi: {
    info: {
      title: 'Fun Quotes API',
      description: 'A fun API for random quotes and facts',
      version: '1.0.0'
    },
    servers: [
      {
        url: `http://localhost:${process.env.PORT || 3000}`
      }
    ]
  }
})

app.register(require('@fastify/swagger-ui'), {
  routePrefix: '/docs'
})

// Register routes
app.register(require('./routes/quotes'))
app.register(require('./routes/facts'))

// Health check route
app.get('/health', async (request, reply) => {
  return { status: 'ok', uptime: process.uptime() }
})

// Start the server
const start = async () => {
  try {
    await app.listen({ port: process.env.PORT || 3000, host: '0.0.0.0' })
    app.log.info(`Server listening on ${app.server.address().port}`)
  } catch (err) {
    app.log.error(err)
    process.exit(1)
  }
}

start() 